package zjc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import zjc.dao.LiuyanDao;
import zjc.dao.UserDao;
import zjc.domain.Liuyan;
import zjc.domain.User;

import java.text.SimpleDateFormat;
import java.util.List;

@Controller
public class LiuyanController {

    @Autowired
    private LiuyanDao liuyanDao;
//test
    @Autowired
    private UserDao userDao;

    @GetMapping("/addliuyan")
    public String add(Model model) {
        List<User> users = userDao.findAll();
        model.addAttribute("users", users);
        model.addAttribute("liuyan", new Liuyan());
        return "liuyan/addLiuyan";
    }

    @PostMapping("/liuyan/addliuyan")
    public String addliuyan(Liuyan liuyan) {
        if (liuyan.getTitle().isEmpty()) {
            return "liuyan/inputEmptyTitle";
        } else if (liuyan.getDetails().isEmpty()) {
            return "liuyan/inputEmptyDetails";
        } else if (!isDateValid(liuyan.getLydate())) {
            return "liuyan/inputErrorDate";
        }
        liuyan.setUserId(liuyan.getUser().getId());
        liuyanDao.save(liuyan);
        return "liuyan/SuccessAddly";
    }

    public static boolean isDateValid(String date) {
        String dateFormat = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        sdf.setLenient(false);
        try {
            sdf.parse(date);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @GetMapping("/listliuyan")
    public String list(Model model) {
        List<Liuyan> liuyans = liuyanDao.findAll();
        model.addAttribute("liuyans", liuyans);
        return "liuyan/listLiuyan";
    }

    @GetMapping("/liuyan/update/{id}")
    public String update(@PathVariable long id, Model model) {
        Liuyan liuyan = liuyanDao.findById(id);
        model.addAttribute("liuyan", liuyan);
        return "liuyan/Updateliuyan";
    }

    @GetMapping("/liuyan/delete/{id}")
    public String delete(@PathVariable Long id) {
        liuyanDao.delete(id);
        return "liuyan/Successdelete";
    }

    @PostMapping("/liuyan/update")
    public String updateliuyan(Liuyan liuyan) {
        if (!isDateValid(liuyan.getLydate())) {
            return "liuyan/inputErrorDate";
        }
        liuyanDao.update(liuyan);
        return "liuyan/SuccessUpdate";
    }
}
